﻿using AopFilters.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AopFilters
{
    /// <summary>
    /// 结果AOP 用于渲染请求结果（对请求结果的统一处理 或json格式的统一处理）
    /// </summary>
    public class KmAsyncResultFilter : IAsyncResultFilter
    {
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.IfIgnoreFilter(typeof(KmAsyncResultFilter)))
            {
                await next.Invoke();
                return;
            }
            //结果之前
            Console.WriteLine("【ResultFilter】 开始...");

            if (context.Result is EmptyResult _e)
            {
                context.Result = new ObjectResult(ApiResult.Success());
            }
            if (context.Result is ObjectResult _o)
            {
                if (_o.Value is ApiResult) { }
                else
                    context.Result = new ObjectResult(ApiResult.Success(_o.Value));
            }
            var objectresult = context.Result as ObjectResult;
            var cotentresult = new ContentResult()
            {
                Content = JsonConvert.SerializeObject(objectresult.Value),
                ContentType = "application/json",
                StatusCode = 200
            };
            context.Result = cotentresult;

            await next.Invoke();
            Console.WriteLine("【ResultFilter】 结束...");
        }
    }
}
